//
//  NIDropDownList.m
//  AccuroScale
//
//  Created by Yongfeng Li on 4/4/14.
//  Copyright (c) 2014 Yongfeng Li. All rights reserved.
//

#import "AppDelegate.h"
#import "NIDropDownList.h"
#import "HrdRcdViewCtrl.h"
#import <AudioToolbox/AudioServices.h>

#define _rowHgt 40
#define _nCountLimt 8

static BOOL _bDeleteItem;
static NSInteger _nTableEditRow = -1;
//static UISegmentedControl* _scItem = nil;


/*@interface NIDropDownList ()
@property(nonatomic, strong) UITableView *table;
@property(nonatomic, strong) UIButton *btnSender;
@property(nonatomic, retain) NSArray *list;
@property(nonatomic, retain) NSArray *imageList;
@end*/
/************************/
/*     about _nType     */
/*   =0, entry view     */
/*   =9: user wgt sel   */
/*   =10: fix menu      */
/*   =11: wifi setup    */
/************************/

@implementation NIDropDownList {
  BOOL _isPopup;
  short _nType;
  int _nProdSelIds;
  NSUInteger _nItemCount;
  
  NSString* _sSelText;
  NSString* _sSelValId;
  NSInteger _nSelectIdx;
  
  CGRect _popupRect;
  CGRect _hideRect;
    
  NSString* _sCurConnBLeDev;
  NSDictionary* _dirList;
  
  NSArray* _sortedKeys;
  NSArray* _sortedVals;
  //NIDropDownListCellsBlock _cells;
    
  UITableView *_table;
    
  //NSString* _animationDirection;

  NSString* _sCurBodyId;
  UIImage* _imgCurSel;
  UIImage* _imgEmpty;    
  BOOL _bAccessTypeReg;
  BOOL _bIniChooseDevice;
  BOOL _bDeviceOwner;
  
  BOOL _bClearData;
  //UIImageView* _ivLeftArrow;
  
  UIView* _pViewRow;
  UIButton* _btnRowDel;
  UIButton* _btnRowUpld;
  
  BOOL _bSmallScr;
  BOOL _bIpad;
  BOOL _bIp4s;
  
  BOOL _bStoreLoc;
}

@synthesize isPopup = _isPopup;
@synthesize sSelValId = _sSelValId;
/*@synthesize table;
@synthesize btnSender;
@synthesize list;
@synthesize imageList;
@synthesize delegate;
@synthesize animationDirection;*/

- (id)initWithFrame:(CGRect)frame type:(short) nType
{
  _nType = nType;
  _nProdSelIds = 0;
  _nItemCount = 0;

  CGFloat W = frame.size.width;
  CGFloat H = frame.size.height;
  
  _bSmallScr = W <= 312;
  _bIpad = W == 379 || W == 402 || W == 508;
  _bIp4s =  (H == 160 || H == 325) && (W == 225);
  
    self = [super initWithFrame:frame];
    if (self) {
      // Initialization code
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      _nSelectIdx = 0;
      _sCurBodyId = @"";
      if(pApp.m_nLastHrtId > 0)
        _sSelValId = [NSString stringWithFormat:@"%ld", (long)pApp.m_nLastHrtId];
      [self setFrameRect:frame];
      //self.backgroundColor = [UIColor grayColor];
        
        _table = [[UITableView alloc]init];
        _table.layer.cornerRadius = 5;
        if(nType == 0) {
            _table.backgroundColor = [UIColor clearColor];
            _table.separatorColor = [UIColor lightGrayColor];
        }
        else if(nType == 8) {
            //self.backgroundColor = [UIColor lightGrayColor];
            _table.backgroundColor = [UIColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:0.5];
            _table.separatorColor = [UIColor whiteColor];
        }
        else if(nType == 11) {
          _table.backgroundColor = [UIColor colorWithRed:0.25 green:0.25 blue:0.25 alpha:0.5];
          _table.separatorColor = [UIColor whiteColor];
        }
        else if(nType == 101) {
          self.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.8];
          _table.backgroundColor = [UIColor whiteColor];// [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.8];
          _table.separatorColor = [UIColor whiteColor];
        }
        else if(nType >= 99) {
          CGFloat fColPart = 0.5, fAlpha = 0.5;
          _bStoreLoc = frame.origin.x <= 25;
          if(_bIpad)
            _bStoreLoc = frame.size.width = 508;
          if(_bStoreLoc) {
            fColPart = 0.125;
            fAlpha = 1.0;
          }
          _table.backgroundColor = [UIColor whiteColor];//[UIColor colorWithRed:fColPart green:fColPart blue:fColPart alpha:fAlpha];
          _table.separatorColor = [UIColor whiteColor];
        }
        else {
            _table.backgroundColor = [UIColor lightGrayColor];//[UIColor colorWithRed:0.25 green:0.25 blue:0.25 alpha:0.75];
            _table.separatorColor = [UIColor whiteColor];
            _table.separatorColor = [UIColor grayColor];
        }
        //_table.separatorColor = [UIColor grayColor];
        _table.delegate = self;
        _table.dataSource = self;
      
      if(nType == 101) {
        _table.rowHeight = _rowHgt * 1.2;//(nType == 8 || _nType == 10)?(_rowHgt-6): _rowHgt;
        //_table.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched; //UITableViewCellSeparatorStyleSingleLine;
      }
      else
        _table.rowHeight = _rowHgt;
        _table.frame = CGRectMake(0, 0, _popupRect.size.width, 0);
        if(nType == 10) {
            //_table.backgroundColor = [UIColor colorWithRed:0.98 green:0.4 blue:0.1 alpha:0.5];
            _table.layer.cornerRadius = 5;
        }
        [self addSubview:_table];
        
        if(nType == 8)
            _imgCurSel = [UIImage imageNamed:@"ic_rfid_l.png"];
        else
            _imgCurSel = [UIImage imageNamed:@"ic_check.png"];
        _imgEmpty = [UIImage imageNamed:@"ic_empty.png"];
    }
    _bAccessTypeReg = YES;
    _bIniChooseDevice = NO;
    
  _sCurConnBLeDev = @"";
    
  _dirList = nil;
  _sortedKeys = nil;
  _sortedVals = nil;
    
  _bClearData = NO;
  
  //_ivLeftArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"act-leftArrow.png"]];
  _pViewRow = nil;
  _btnRowDel = nil;
  _btnRowUpld = nil;
  
  _table.delaysContentTouches = NO;
  
  return self;
}

- (void) setTableRect:(CGRect)frame
{
    _popupRect = frame;
}

- (void) setFrameRect:(CGRect)frame
{
    [self hideDropDownList];
    self.frame = frame;
    _popupRect = self.frame;
    self.layer.masksToBounds = NO;
    self.layer.cornerRadius = 2;
    if(_nType == 8) {
        self.layer.shadowRadius = 3;
        self.layer.shadowOpacity = 0.55;
    }
    else if(_nType != 10) {
        self.layer.shadowRadius = 5;
        self.layer.shadowOpacity = 0.5;
    }
    else {
        self.layer.shadowRadius = 2;
        self.layer.shadowOpacity = 0.05;
    }
    _hideRect = CGRectMake(_popupRect.origin.x, _popupRect.origin.y + _popupRect.size.height, _popupRect.size.width, 0);
    self.frame = _hideRect;
    _isPopup = NO;
}

/*- (NSComparisonResult)compare: (NSDictionary *)otherDictionary
{
    NSDictionary *tempDictionary = (NSDictionary *)self;
    
    NSNumber *number1 = [[tempDictionary allKeys] objectAtIndex:0];
    NSNumber *number2 = [[otherDictionary allKeys] objectAtIndex:0];
    
    NSComparisonResult result = [number1 compare:number2];
    
    return result == NSOrderedDescending; // 升序
}*/

-(void) setListData:(NSDictionary *)dirList curSel:(NSString*)sBodyId
{
  if(dirList == nil) {
    _bClearData = YES;
    return;
  }
  _dirList = nil;
  
  _sortedKeys = nil;
  _sortedVals = nil;
  /*if(_sortedKeys != nil && [_sortedKeys count])
    [_sortedKeys removeAllObjects];
  if(_sortedVals != nil && [_sortedVals count])
    [_sortedVals removeAllObjects];*/

  _nItemCount = dirList.count;
  _dirList = [dirList copy];//[NSDictionary dictionaryWithDictionary:dirList];

  if(_nType == 100) {
    NSArray* keys = [_dirList allKeys];
    NSArray* sortedKeys = [keys sortedArrayUsingComparator:^(id a, id b) {
      return [b compare:a options:NSNumericSearch];
    }];
    _sortedKeys = [sortedKeys copy];
  }
  else if(_nType != 99 && _nType != 101) {
    NSArray* keys = [_dirList allKeys];
    NSArray* sortedKeys = [keys sortedArrayUsingComparator:^(id a, id b) {
      return [a compare:b options:NSNumericSearch];
    }];
    _sortedKeys = [sortedKeys copy];
  }
  else if(_nType == 101) { //sort
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    NSDateFormatter* dtFmt = pApp.dtFmt;
    [dtFmt setDateFormat:@"MM/dd/yy HH:mm:ss"];
    NSArray* sortedValues = [dirList keysSortedByValueUsingComparator:^(id a, id b) {
      NSString* sAtxt = a;
      NSString* sBtxt = b;
      
      sAtxt = [sAtxt substringWithRange: NSMakeRange(0, 17)];
      sBtxt = [sBtxt substringWithRange: NSMakeRange(0, 17)];
      NSDate* dtA = [dtFmt dateFromString:sAtxt];
      NSDate* dtB = [dtFmt dateFromString:sBtxt];
      return [dtB compare:dtA];
      //return [b compare:a];
    }];
    _sortedKeys = [sortedValues copy];
    
    [ pApp.dtFmt setDateFormat:sInitDtFmt];
    /*NSArray* keys = [_dirList allKeys];
    NSArray* sortedKeys = [keys sortedArrayUsingComparator:^(id a, id b) {
     return [b compare:a options:NSNumericSearch];
    }];
    _sortedKeys = [sortedKeys copy];*/
  }
  else {
    //if(!_bStoreLoc && _dirList != nil && _dirList.count > 0) {
      NSArray* keys = [_dirList allKeys];
      NSArray* sortedKeys = [keys sortedArrayUsingComparator:^(id a, id b) {
        //return [a compare:b options:NSNumericSearch];
        return [a compare:b];
      }];
      _sortedKeys = [sortedKeys copy];
    /*}
    else {
      _sortedKeys = [_dirList copy];//[dirList copy];
    }*/
  }

  /*}
  if(_nType == 0 ||  _nType == 8 || _nType == 10) {
    _sortedKeys = [[_dirList allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
  }
  else {
    _sortedKeys = [_dirList keysSortedByValueUsingSelector:@selector(caseInsensitiveCompare:)];
  }*/
    
  if(sBodyId != nil) {
    _sCurBodyId = [NSString stringWithString:sBodyId];
    _sSelValId = sBodyId;
  }
  else {
    _sCurBodyId = @"-1";
    _sSelValId = @"-1";
  }
  
  [_table reloadData];
}

-(void) setOptionData:(NSArray *)arrList curSel:(NSString*)sBodyId
{
    _sortedKeys = [arrList copy];
    _sCurBodyId = sBodyId;
    _sSelValId = _sCurBodyId;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

/*- (void) setMenuAppearance
{
    _table.backgroundColor = [UIColor clearColor];
    if(_nType >= 9) {
        NSIndexPath *first=[NSIndexPath indexPathForRow:0 inSection:0];
        [_table selectRowAtIndexPath:first animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
}*/

/*- (id)showDropDownList:(UIView *)btnItem hgt:(CGFloat *)fHgt data:(NSArray *)arr img:(NSArray *)iArr dir:(NSString *)direction
{
    _btnSender = btnItem;
    _animationDirection = direction;
    _table = (UITableView *)[super init];
    if (self) {
        // Initialization code
        CGRect btn = btnItem.frame;
        btn.origin.x = 20;
        btn.origin.y = 50;
        btn.size.height = 20;
        btn.size.width = 260;
        
        _list = [NSArray arrayWithArray:arr];
        self.list = _list;
        _imageList = [NSArray arrayWithArray:iArr];
        self.imageList = _imageList;
        if ([direction isEqualToString:@"up"]) {
            self.frame = CGRectMake(btn.origin.x, btn.origin.y, btn.size.width, 0);
            self.layer.shadowOffset = CGSizeMake(-5, -5);
        }else if ([direction isEqualToString:@"down"]) {
            self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, 0);
            self.layer.shadowOffset = CGSizeMake(-5, 5);
        }
        
        self.layer.masksToBounds = NO;
        self.layer.cornerRadius = 8;
        self.layer.shadowRadius = 5;
        self.layer.shadowOpacity = 0.5;
        
        table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, btn.size.width, 0)];
        table.delegate = self;
        table.dataSource = self;
        table.layer.cornerRadius = 5;
        table.backgroundColor = [UIColor colorWithRed:0.539 green:0.539 blue:0.539 alpha:1];
        table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        table.separatorColor = [UIColor whiteColor];
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        if ([direction isEqualToString:@"up"]) {
            self.frame = CGRectMake(btn.origin.x, btn.origin.y-*fHgt, btn.size.width, *fHgt);
        } else if([direction isEqualToString:@"down"]) {
            self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, *fHgt);
        }
        table.frame = CGRectMake(0, 0, btn.size.width, *fHgt);
        [UIView commitAnimations];
        [btnItem addSubview:self];
        [self addSubview:table];_rowHgt
    }
    return self;
}*/
- (void) showDropDownList:(NSDictionary *)dirList curSel:(NSString*)sBodyId
{
    _isPopup = YES;
    //self.hidden = !_isPopup;
    
    NSUInteger nCount = [dirList count];
    _dirList = [NSDictionary dictionaryWithDictionary:dirList];
    if(_nType > 6)
        _sortedKeys = [[_dirList allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
    else
        _sortedKeys = [_dirList keysSortedByValueUsingSelector:@selector(caseInsensitiveCompare:)];
    //self.list = _list;
    _sCurBodyId = sBodyId;
    _sSelValId = _sCurBodyId;
    
    /*[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.2];
	[UIView setAnimationCurve:UIViewAnimationCurveLinear];
	[UIView commitAnimations];*/
    
    CGRect rt = _popupRect;
    rt.origin.x = 0;
    rt.origin.y = 0;
    
  CGFloat fRowHgt = _rowHgt * ((_nType == 101)?1.2:1);
    //if(_nType == 8)
        //fRowHgt -= 6;
    if((_nType == 1 || _nType == 8) && nCount < 10) {
        rt.size.height = nCount * fRowHgt;
        _popupRect.size.height = rt.size.height;
        _hideRect = CGRectMake(_popupRect.origin.x, _popupRect.origin.y + _popupRect.size.height, _popupRect.size.width, 0);
    }
    
  _table.rowHeight = fRowHgt * ((_nType = 101)?1.2:1.0);//(_nType == 8 || _nType == 10)?(_rowHgt-6): _rowHgt;
    [self setFrame:_popupRect];
    [_table setFrame:rt];
  
    
    //[UIView commitAnimations];
    [_table reloadData];
}

-(void) popupDropDownList
{
    _isPopup = YES;
    [_table removeFromSuperview];
    
     NSUInteger nCount = [_dirList count];
    if(nCount == 0)
        nCount = _sortedKeys.count;
    if(_nType == 9 || _nType == 11 || _nType == 99 || _nType == 101) {
        nCount = nCount + 1;
    }
    
  /*[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.2];
	[UIView setAnimationCurve:UIViewAnimationCurveLinear];
	[UIView commitAnimations];*/
  
  CGRect rt = _popupRect;
  rt.origin.x = 0;
  rt.origin.y = 0;
    
  CGFloat fRowHgt = _rowHgt * ((_nType == 101)?1.2:1);//(/*_nType == 8 || */_nType == 10)?(_rowHgt-6): _rowHgt;
  NSUInteger nCountLimt = (_nType == 101)?_nCountLimt:_nCountLimt;
  if(_bIpad)
    nCountLimt = _nCountLimt + 2;
  else if(_bIp4s)
    nCountLimt = 5;
  else
    nCountLimt = _nCountLimt + 3;
  
  //BOOL bMoreSize = (nCountLimt * fRowHgt + fRowHgt) >= _popupRect.size.height;
  /*if(_nType != 0 && nCount <= nCountLimt) {
    if(bMoreSize)
      rt.size.height =  nCountLimt * fRowHgt + fRowHgt;
    else
      rt.size.height = nCount * fRowHgt;
    _popupRect.size.height = rt.size.height;
    _hideRect = CGRectMake(_popupRect.origin.x, _popupRect.origin.y + _popupRect.size.height, _popupRect.size.width, 0);
  }
  else {
    if(_nType == 100)
      rt.size.height = _popupRect.size.height;
    else if(_nType == 99)
      rt.size.height = _popupRect.size.height;
    else if(bMoreSize)
      rt.size.height = nCountLimt * fRowHgt + fRowHgt;
    else
      rt.size.height = nCountLimt * fRowHgt + fRowHgt;//_popupRect.size.height;
    _hideRect = CGRectMake(_popupRect.origin.x, _popupRect.origin.y + _popupRect.size.height, _popupRect.size.width, 0);
  }*/
  rt.size.height = nCountLimt * fRowHgt + fRowHgt;
  _hideRect = CGRectMake(_popupRect.origin.x, _popupRect.origin.y + _popupRect.size.height, _popupRect.size.width, 0);
    
  //_popupRect = rt;
  
  _table.rowHeight = fRowHgt;
  [self setFrame:_popupRect];
  [_table setFrame:rt];
  
  //rt.size.height += 4;
  //self.frame = rt;
    
  //[UIView commitAnimations];
  [_table reloadData];
    
  if(_nType == 0) {
    _nProdSelIds = 0;
    _bAccessTypeReg = YES;
    _bIniChooseDevice = NO;
  }
  
  //CGFloat fColPart = (_nType==11)?0.25:0.5;
  //_table.backgroundColor = [UIColor colorWithRed:fColPart green:fColPart blue:fColPart alpha:0.5];
  [self addSubview:_table];
}

/*- (void)popupOption:(NSDictionary *)dirList curSel:(NSString*)sBodyId andCells:(NIDropDownListCellsBlock)cellsBlock
{
    _cells = cellsBlock;
    [_table reloadData];
}*/

-(void)hideDropDownList {
  _isPopup = NO;
    
  [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.2];
	[UIView setAnimationCurve:UIViewAnimationCurveLinear];
	[self setFrame:_hideRect];
  [_table setFrame:CGRectMake(0, 0, _popupRect.size.width, 0)];
	[UIView commitAnimations];
    
     //self.hidden = !_isPopup;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //return (_nType == 0)? 2: 1;
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_nType == 0) {
        return (section==0)? 0:35.0f;
    }
    else if (_nType == 9 || _nType == 99 ||  _nType == 101) {
        return _rowHgt * ((_nType == 101)?1.2:1.0);
    }
    else {
        //return [tableView tableView:_table heightForHeaderInSection:section];
        return 0;//_table.frame.size.height;
    }
}


//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
- (NSString *)tableView:(UITableView *)table titleForHeaderInSection:(NSInteger)section
{
  if (table == _table)
  {
    if (section == 0) {
      if(_nType == 9)
        return NSLocalizedString(@"Wgt", nil);
      else if(_nType == 11)
        return @"Store Locaion";
      else if(_nType == 99 || _nType == 101)
        return NSLocalizedString(@"Please select one", nil); //NSLocalizedString(@"PlsSelHrm", nil);//(@"BLE List", nil);
      else
        return nil;
    }
    else if (section == 1) {
      return NSLocalizedString(@"AccessType", nil);//@"Access Type";
    }
    else
      return nil;
  }
  else {
    return (_nType == 11)?@"Store Location": nil;
  }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return _rowHgt * ((_nType == 101)?1.2:1.0);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  if(_bClearData)
    return 0;
    
  if(_nType == 0) {
    return (section == 0)? _dirList.count: 2;//self.numberOfRows(section);//_sortedKeys.count;
  }
  else if(_nType == 101) {
    NSInteger nCount = _sortedKeys.count;
    return nCount;
  }
  else if(_dirList != nil) {
    return _dirList.count;
  }
  else {
    return 0;
  }
    //return _dirList.count;
}

- (void) setProdSelMakrs:(UITableViewCell*) cell rowIdx:(int) nRowIdx curIdx:(int)nCurIdx
{
    /*if(_bAccessTypeReg) {
        cell.backgroundColor = [UIColor clearColor];
        cell.imageView.image = _imgEmpty;
        return;
    }
    else if(_bIniChooseDevice) {
        //_bTapAccessType = NO;
        return;
    }
    
    int nIdx = nCurIdx - 1;
    cell.backgroundColor = [UIColor clearColor];
    if(nIdx < 0) {
        cell.imageView.image = _imgEmpty;
        return;
    }
    //nRowIdx += 1;
    
    Byte nBitCal =  0;
    if (nRowIdx == nIdx)
        nBitCal = 1 << nIdx;
    _nProdSelIds = _nProdSelIds ^ nBitCal;
    
    nBitCal = _nProdSelIds & (1<<nRowIdx);
    cell.imageView.image = (nBitCal > 0)?_imgCurSel: _imgEmpty;*/
    
    int nIdx = nCurIdx - 1;
    if(nIdx < 0) {
        cell.imageView.image = _imgEmpty;
        return;
    }
    //nRowIdx += 1;
    
    //Byte nBitCal =  0;
    if (nRowIdx == nIdx)
        cell.imageView.image = _imgCurSel;
    else
        cell.imageView.image = _imgEmpty;
    _nProdSelIds = nCurIdx;
}

- (HrdRcdViewCtrl *)parentViewController {
  UIResponder *responder = self;
  while ([responder isKindOfClass:[UIView class]])
    responder = [responder nextResponder];
  return (HrdRcdViewCtrl *)responder;
}

- (UIImageView*) getRightImgView:(short)nIdx vctrl:(HrdRcdViewCtrl*)pVctrl;
{
  short nActType = [pVctrl getActTypeIdx:nIdx];
  UIImage* iRight = (nActType == 0)?[UIImage imageNamed:@"act-swipe.png"]: [pVctrl getActTypeImage:nIdx];
  UIImageView* ivRight = [[UIImageView alloc] initWithImage: iRight];
  CGRect rt = CGRectMake(0, 0, _rowHgt * 2 / 3,  _rowHgt * 2 / 3);
  ivRight.frame = rt;
  return ivRight;
}

- (void) deleteOneRow:(NSInteger)nIdx
{
  BOOL bIos8 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0;
  if(bIos8) {
    HrdRcdViewCtrl* pvCtrl = [self parentViewController];
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* deleteAction = [UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive
                                                         handler:^(UIAlertAction * action) {
                                                           /*AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                                                            NSInteger nIdx = ((UIButton*)sender).tag;
                                                            NSString* sKey = [_sortedKeys objectAtIndex:nIdx];
                                                            NSInteger nHrateId = sKey.integerValue;
                                                            
                                                            //test
                                                            //HrdRcdViewCtrl* pvCtrl = [self parentViewController];
                                                            //[pvCtrl showSyncOption:sKey];
                                                            //return;
                                                            
                                                            //[_table beginUpdates];
                                                            [self deleteHrateRow:nHrateId row:nIdx];
                                                            //if(indexPath.section > 0)
                                                            //[_table deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];*
                                                            pApp.m_nLastHrtId = 0;
                                                            pApp.m_nLastHrate = 0;
                                                            pApp.m_nCurtAvgHrt = 0;
                                                            
                                                            [pvCtrl reloadHrateData];
                                                            
                                                            //[_sortedKeys delete:];
                                                            [_table reloadData];*/
                                                           [self onDeleteHrtRowData:nIdx];//((UIButton*)sender).tag];
                                                         }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                           [_table setEditing:NO];
                                                         }];
    
    [alert addAction:deleteAction];
    [alert addAction:cancelAction];
    
    if(pvCtrl != nil)
      [pvCtrl presentViewController:alert animated:YES completion:nil];
  }
  else {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Delete comfirm" message:@"Are you sure to delte the item!" delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@"Delete", nil];
    alertView.tag = nIdx;//((UIButton*)sender).tag;
    [alertView show];
    
    /*alertView.Clicked += (object senders, UIButtonEventArgs es) =>
     {
     if (es.ButtonIndex == 0 ) {
     // do something if cancel
     }else
     {
     // Do something if yes
     }
     };*/
  }
}

- (void)tapImgBtnDelete:(id)sender
{
  NSInteger nIdx = ((UIButton*)sender).tag;
  [self deleteOneRow:nIdx];

}

- (void) onDeleteHrtRowData:(NSInteger)nIdx
{
  HrdRcdViewCtrl* pvCtrl = [self parentViewController];
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //NSInteger nIdx = ((UIButton*)sender).tag;
  NSString* sKey = [_sortedKeys objectAtIndex:nIdx];
  NSInteger nHrateId = sKey.integerValue;
  
  //test
  //HrdRcdViewCtrl* pvCtrl = [self parentViewController];
  //[pvCtrl showSyncOption:sKey];
  //return;
  
  //[_table beginUpdates];
  [self deleteHrateRow:nHrateId row:nIdx];
  //if(indexPath.section > 0)
  //[_table deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];*
  pApp.m_nLastHrtId = 0;
  pApp.m_nLastHrate = 0;
  pApp.m_nCurtAvgHrt = 0;
  
  //send info to svr
  [pvCtrl sendSvrUserDelHrate:nHrateId];
  
  pApp.m_nLstHrtIdx = 0;
  //data refresh
  [pvCtrl reloadHrateData];
  [_table reloadData];
  
  if(nHrateId < 0)
  [pApp DeleteEnableDownload: YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
  if(buttonIndex == 1) { //delete
    [self onDeleteHrtRowData:alertView.tag];
  }
  //NSString* sMsg = [NSString stringWithFormat:@"select:%ld", (long)buttonIndex];
  //UIAlertView* selView = [[UIAlertView alloc] initWithTitle:@"Delete selet" message:sMsg delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
  //[selView show];
}

- (void)tapImgBtnUpld:(id)sender
{
  HrdRcdViewCtrl* pVCtrl = [self parentViewController];
  NSInteger nIdx = ((UIButton*)sender).tag;
  NSString* sKey = [_sortedKeys objectAtIndex:nIdx];
  NSInteger nHrateId = sKey.integerValue;
  NSString* sMsg = [self getItemText:nIdx key:&sKey];
  
  _sSelValId = sKey;
  //self.sSelValId = sKey;
  NSString* sText = [_dirList objectForKey: sKey];
  NSRange rng = [sText rangeOfString: @"->"];
  if(rng.location != NSNotFound)
    _sSelText = [sText substringWithRange:NSMakeRange(0, rng.location)];
  _nSelectIdx = nIdx;
  
  [self DlistDelegate];
  [pVCtrl showSyncOption:(NSInteger)nHrateId idx: nIdx msg:sMsg type:0];
}

- (UIView*) getRowButsView:(short)nIdx vctrl:(HrdRcdViewCtrl*)pVctrl
{
  CGFloat W = self.frame.size.width; //ip5/5s 298, iP6:351, iP6p:390
  
  CGFloat fHgt = _rowHgt * ((_nType == 101)?1.2:1);
  CGRect rt = CGRectMake(0, 0, _rowHgt * 5.0 + (W-390),  fHgt);
  _pViewRow = [[UIView alloc] initWithFrame:rt];
  
  //short nActType = [pVctrl getActTypeIdx:nIdx];
  //UIImage* iRight = (nActType == 0)?[UIImage imageNamed:@"act-swipe.png"]: [pVctrl getActTypeImage:nIdx];
  UIImage* iRight = [pVctrl getActTypeImage:nIdx];
  UIImageView* ivRight = [[UIImageView alloc] initWithImage: iRight];
  rt.origin.x = 0;
  rt.origin.y = 8;
  rt.size.width = _rowHgt * 0.8;
  rt.size.height = _rowHgt * 0.8;
  ivRight.frame = rt;
  [_pViewRow addSubview:ivRight];
  
  rt.origin.x += _rowHgt * 3.2 + (W-390);
  rt.origin.y = 6;
  
  //upload btn
  //rt.origin.y =  _rowHgt - 4;
  UIImage* iBtn = [UIImage imageNamed:@"btn-hrtUpld.png"];
  UIButton*  pButUpd = [[UIButton alloc] initWithFrame:rt];
  [pButUpd setBackgroundImage:iBtn forState:UIControlStateNormal];
  pButUpd.tag = nIdx;
  [pButUpd addTarget:self action:@selector(tapImgBtnUpld:) forControlEvents:UIControlEventTouchUpInside];
  [_pViewRow addSubview:pButUpd];
  
  //delete btn
  rt.origin.x += _rowHgt * 1.25;
  rt.origin.y = 2;
  rt.size.width += _rowHgt * 0.20;
  rt.size.height += _rowHgt * 0.15;
 
  //rt.size.height = _rowHgt  - 2;
  iBtn = [UIImage imageNamed:@"ic-trash.png"];
  _btnRowDel = [[UIButton alloc] initWithFrame:rt];
  _btnRowDel.tag = nIdx;
  
  CGFloat xOffset = _bSmallScr?30:20;
  //[_btnRowDel setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
  _btnRowDel.imageEdgeInsets = UIEdgeInsetsMake(0, -xOffset, -4, 0);
  //[_btnRowDel setTitle:@"Del" forState:UIControlStateNormal];
  //®_btnRowDel.backgroundColor = [UIColor lightGrayColor];
  [_btnRowDel setImage:iBtn forState:UIControlStateNormal];
  [_btnRowDel addTarget:self action:@selector(tapImgBtnDelete:) forControlEvents:UIControlEventTouchUpInside];
  [_pViewRow addSubview:_btnRowDel];
  
  return _pViewRow;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
  static NSString *CellIdentifier = @"Cell";
  //NSInteger nIdx = indexPath.row;

  
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.textLabel.font = [UIFont systemFontOfSize:_bSmallScr?15:16];
    cell.textLabel.textAlignment = NSTextAlignmentLeft;//NSTextAlignmentCenter;//UITextAlignmentCenter;
    //cell.frame = CGRectMake(0.0f, 0.0f, 320.0f, _rowHgt);
    //cell.accessoryType = UITableViewCellAccessoryDetailButton; //UITableViewCellAccessoryDisclosureIndicator;
  }
  if(_nType == 101) {
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    cell.textLabel.numberOfLines = 2;
    
    //cell.frame = CGRectMake(0, 0,_table.bounds.size.width, _rowHgt * 2 - 4);
    CALayer *separator = [CALayer layer];
    separator.backgroundColor = [UIColor lightGrayColor].CGColor;
    separator.frame = CGRectMake(0, _rowHgt*1.2-2, _table.frame.size.width, 1);
    [cell.layer addSublayer:separator];
    
    HrdRcdViewCtrl* pVCtrl = [self parentViewController];
    /*UIImageView* ivLeftArrow  = [self getRightImgView:indexPath.row vctrl:pVCtrl];
    if(ivLeftArrow != nil)
     cell.accessoryView = ivLeftArrow;*/
     
    UIView* pButsView = [self getRowButsView:indexPath.row vctrl:pVCtrl];
    if(pButsView != nil) {
      cell.accessoryView = pButsView;
    }
  }
   
  NSString* key = @"";
  NSString* value = @"";
  if(_sortedKeys != nil) {
    NSArray * keySort = _sortedKeys;//[_dirList keysSortedByValueUsingSelector:@selector(caseInsensitiveCompare:)];
    key = [keySort objectAtIndex: indexPath.row];
    value = [_dirList objectForKey: key];
  }
  else {
    NSArray* valList = _sortedVals;
    value = [valList objectAtIndex:indexPath.row];
    key = @"0";//[_dirList objectAtIndex: indexPath.row];
  }
  if(_nType == 101) {
    /*NSRange rngCov = [value rangeOfString:@"->"];
    if(rngCov.location != NSNotFound) {
      NSString* sHrateId =[value substringWithRange: NSMakeRange(rngCov.location+2, value.length-rngCov.location-2)];
       value = [value substringWithRange: NSMakeRange(0, rngCov.location)];
       
       if(sHrateId.integerValue < 0) {//not upload
         cell.backgroundColor= [UIColor grayColor];
       }
    }*/
    
    //NSRange rngUpd = [value rangeOfString:NSLocalizedString(@"OK", nil)];
    NSRange rngIdx = [value rangeOfString: @"LstIdx"];
    if(rngIdx.location != NSNotFound) {
      NSRange rngSynct = [value rangeOfString:@"&st="];
      short nSyncType = 0;
      NSInteger nLastIdx = 0;
      if(rngSynct.location != NSNotFound) {
        //NSInteger nPos = rngSynct.location;
        NSString* sLastIdx = [value substringWithRange:NSMakeRange(rngIdx.location+7, rngSynct.location-rngIdx.location-7)];
        NSString* sSyncType = [value substringWithRange:NSMakeRange(rngSynct.location+rngSynct.length, value.length-rngSynct.location-rngSynct.length)];
        nLastIdx = sLastIdx.integerValue;
        nSyncType = (short)sSyncType.intValue;
      }
      //if(nLastIdx == 0)
        //cell.backgroundColor = (nSyncType ==  1)?[UIColor brownColor]:[UIColor grayColor];
      if((nSyncType == 2 || nLastIdx == -2) && nLastIdx != -1)
        cell.backgroundColor = [UIColor grayColor];
      else if(nLastIdx == 0)
        cell.backgroundColor = [UIColor brownColor];
      else if(nLastIdx > 0 && nSyncType != 0)
        cell.backgroundColor = (nSyncType==2)?[UIColor orangeColor]:[UIColor redColor];
      else
        cell.backgroundColor = [UIColor whiteColor];
      
      
      
      rngIdx = [value rangeOfString: @"->"];
      if(rngIdx.location != NSNotFound)
        value = [value substringWithRange:NSMakeRange(0, rngIdx.location)];
    }
  }
  cell.textLabel.text = value;
    
  bool bSelected = NO;
  if(_nType == 0 /*&& indexPath.section == 0*/) {
    cell.backgroundColor = [UIColor clearColor];
    [self setProdSelMakrs:cell rowIdx:(int)indexPath.row curIdx:_sCurBodyId.intValue];
    return cell;
  }
    
  if(_nType == 99) {
    NSArray	*storedDevices	= [[NSUserDefaults standardUserDefaults] arrayForKey:kSavedHrDevice];
    NSUInteger nCounr = storedDevices.count;
    for(NSInteger i=0; i<nCounr; i++) {
      NSString* uuidString =  [storedDevices objectAtIndex:i];
      BOOL bSame = [uuidString isEqualToString:key];
      //if([uuidString isEqual:key]) {
      if(bSame) {
        bSelected = YES;
        cell.textLabel.textColor = [UIColor orangeColor];
        cell.imageView.image = _imgCurSel;
      }
     
    }
  }
  else if(_nType > 10) {
    if([_sCurBodyId isEqualToString:key] || [_sSelValId  isEqualToString:key]) {
      bSelected = YES;
      cell.textLabel.textColor = [UIColor blueColor];
      //if(_nType != 9)
      cell.imageView.image = _imgCurSel;
    }
  }
  else {
    if([_sCurBodyId integerValue] == [key integerValue]) {
      bSelected = YES;
      cell.textLabel.textColor = [UIColor orangeColor];
      cell.imageView.image = _imgCurSel;
    }
  }
    
  if(!bSelected) {
    if(_nType == 9 || _nType == 99)
      cell.textLabel.textColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.95 alpha:1.0];
    else
      cell.textLabel.textColor = [UIColor blackColor];
      //if(_nType != 9)
    cell.imageView.image = _imgEmpty;
  }
    
  if(_nType == 8) {
    cell.backgroundColor = [UIColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:0.75];//[UIColor clearColor];
    //cell.backgroundColor = [UIColor clearColor];
  }
  else if(_nType == 9) {
    cell.backgroundColor = [UIColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:0.5];//[UIColor clearColor];
  }
  else if(_nType == 10) {
    cell.backgroundColor = [UIColor clearColor]; //redColor];
    //cell.indentationLevel = 1;
    //cell.indentationWidth = -10.0f;
    //CGRect textLabelFrame = cell.textLabel.frame;
    //textLabelFrame.origin.x -= 20;
    //textLabelFrame.size.width -= xOffset;
    //cell.textLabel.frame = textLabelFrame;
    cell.textLabel.textAlignment = NSTextAlignmentLeft;
    cell.textLabel.font = [UIFont systemFontOfSize:16.0];
  }
  else if(_nType == 11) {
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor whiteColor];
  }
  else if(_nType == 99) { //ble abailable list
    CGFloat fSize = 16.0;
    if([[UIScreen mainScreen] bounds].size.width >= 768)
      fSize = 20.0;
    cell.textLabel.font = [UIFont systemFontOfSize:fSize];
    cell.backgroundColor = [UIColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:0.5];
  }
  //UIView * v = [[UIView alloc] init];
  //v.backgroundColor = [UIColor grayColor];
  //cell.selectedBackgroundView = v;
  
  //add swipe to remove and cancel, rihgt and left
  if(_nType == 101) {
    //cell.tag = indexPath.row;
    /*UISwipeGestureRecognizer* swipeRecRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRight:)];
    //[swipeRecRight setDirection:UISwipeGestureRecognizerDirectionLeft+UISwipeGestureRecognizerDirectionRight];
    [swipeRecRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [cell addGestureRecognizer:swipeRecRight];*/
    
    /*UISwipeGestureRecognizer* swipeRecRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRight:)];
    [swipeRecRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [cell addGestureRecognizer:swipeRecRight];*/
    //cell.cell.leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"check.png"] backgroundColor:[UIColor greenColor]],
    //                     [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"fav.png"] backgroundColor:[UIColor blueColor]]];
    
    /*CGRect rt = cell.textLabel.frame;
    rt.origin.x -= 6;
    cell.textLabel.frame = rt;*/
  }
    
  return cell;
}

/*- (void) handleSwipeRight:(id)sender
{
  UISwipeGestureRecognizer *gesture = (UISwipeGestureRecognizer *) sender;
  _nTableEditRow = gesture.view.tag;
  CGRect rt = gesture.view.frame;
  
  rt.origin.y = _rowHgt * (_nTableEditRow + 1) + 2;
  rt.origin.x += rt.size.width / 2;
  rt.size.width /= 2;
  rt.size.height -= 4;
  
  if(_scItem == nil) {
   
    _scItem = [[UISegmentedControl alloc] initWithItems:@[@"Biking", @"Walking", @"Clinbing", @"More..."]];
    _scItem.backgroundColor = [UIColor grayColor];

    [_table addSubview:_scItem];
  }
  _scItem.hidden = NO;
  _scItem.frame = rt;*/
 
  //_nTableEditRow = bDel? gesture.view.tag: -1;
  /*if(_nTableEditRow >= 0) {
    _nTableEditRow = -1;
    
  }
  else {
    _nTableEditRow = gesture.view.tag;
  }
  [_table setEditing:_nTableEditRow>=0 animated:YES];*/
  
  //N_GroupInfo *nGrp = (N_GroupInfo *)[_userArray objectAtIndex:gesture.view.tag];
  //long nBodyId = [nGrp.bodyId integerValue];
  //_lblInfo.text = [NSString stringWithFormat:@"swipe delete: %ld", gesture.view.tag];
  //[_tabView setEditing:YES animated:YES];
//}

- (void) handleSwipeRight:(id)sender
{
  _bDeleteItem = YES;
  UISwipeGestureRecognizer *gesture = (UISwipeGestureRecognizer *) sender;
  if(_nTableEditRow >= 0) {
    _nTableEditRow = -1;
    
  }
  else {
    _nTableEditRow = gesture.view.tag;
    //int n = 2;
  }
  [_table setEditing:_nTableEditRow>=0 animated:YES];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
  // Return YES if you want the specified item to be editable.
  if(_nType == 101)
    return YES; //indexPath.row == _nTableEditRow;
  else
    return NO;
}

/*- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_nType == 10) {
        return -2;
    }
    else {
        //NSUInteger row = indexPath.row;
        return 0;
    }
}*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  if(_dirList == nil && _sortedKeys == nil)
    return;
  if(_dirList.count == 0) //|| _sortedKeys.count == 0)
    return;
  /*if(_nType == 99) {
    [self DlistDelegate];
    return;
  }*/
  NSString* sKey = @"0";
  
  _nSelectIdx = indexPath.row;
  //if(_nSelectIdx >= )
    //return;
  
  _sSelText = [self getItemText: _nSelectIdx key: &sKey];
  _sSelValId = [NSString stringWithString:sKey];
  self.sSelValId = [NSString stringWithString:sKey];
  //NSString* sUuid = self.sSelValId;
      
    //_sSelValId = key;
    //UITableViewCell *c = [tableView cellForRowAtIndexPath:indexPath];
    //[_btnSender setTitle:c.textLabel.text forState:UIControlStateNormal];
    
    /*for (UIView *subview in _btnSender.subviews) {
        if ([subview isKindOfClass:[UIImageView class]]) {
            [subview removeFromSuperview];
        }
    }
    _imgView.image = c.imageView.image;
    _imgView = [[UIImageView alloc] initWithImage:c.imageView.image];
    _imgView.frame = CGRectMake(5, 5, 25, 25);*/
    //_btnSender addSubview:_imgView];
    if(_nType != 0 && _nType < 10)
        [self hideDropDownList];
    
    if(indexPath.section == 1) {
        _nProdSelIds = 0;
        _bAccessTypeReg = indexPath.row == 0;
        //if(!_bAccessTypeReg)
            //[self setProdSelMakrs:cell rowIdx:(int)indexPath.row curIdx:_sCurBodyId.intValue];
    }
    
    _bIniChooseDevice = indexPath.section == 1;
    
    if(_nType == 0) {
        /*BOOL bTips = _bAccessTypeReg && !_bIniChooseDevice ;
        if ([self.delegate respondsToSelector:@selector(accessTypeTapedTip:)])
            [self.delegate accessTypeTapedTip:bTips];
        if(bTips)
            AudioServicesPlaySystemSound(1112);
        else
             AudioServicesPlaySystemSound(1109);*/
        //[_table reloadData];
        AudioServicesPlaySystemSound(1109);

    }
    
    _bDeviceOwner = indexPath.section == 1 && indexPath.row == 1;
    [self DlistDelegate];
  
  //_scItem.hidden = YES;
}

- (void) DlistDelegate
{
  //NSString* sUuid = self.sSelValId;
  _sCurBodyId = [self.delegate niDropDownDelegateMethod:self];
  _sSelValId = _sCurBodyId;
  if(_nType != 0) {
    AudioServicesPlaySystemSound(1109);
  }
}

- (NSString*) getItemText:(NSUInteger)nIdx key:(NSString**) sKey
{
  NSArray* sortedKeys = (_sortedKeys != nil)? _sortedKeys: _dirList.allKeys;
  if(sortedKeys.count == 0 || nIdx >= sortedKeys.count)
    return @"";
  
  NSString* key = [sortedKeys objectAtIndex: nIdx];
  if(key == nil)
    return @"";
  
  NSString* sItemText = [_dirList objectForKey: key];
  NSRange rng = [sItemText rangeOfString:@"->"];
  if(rng.location != NSNotFound) {
    sItemText = [sItemText substringWithRange: NSMakeRange(0, rng.location)];
  }
  
  //*sKey = [NSString stringWithString: key];
  *sKey = [NSString stringWithFormat:@"%@", key];
  return sItemText;
}

- (void) setBkgdColor:(UIColor*)colBkgd
{
    self.backgroundColor = colBkgd;
}
/*-(void)dealloc {
    [super dealloc];
}*/

/*- (void) presentDeleteComfire:(UIAlertController*)alert
{
  [self presentViewController:alert animated:YES completion:nil];
}*/

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
  if(_nType != 101)
    return nil;
  
  [self deleteOneRow:indexPath.row];
  /*UIButton btlDel = nil;
  UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
  for(UIView *view in [cell.accessoryView subviews]) {
    if([view.) {
      [view removeFromSuperview];
    }
  }*/
  return nil;
 
  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //NSString* nHrateId = [_sortedKeys objectAtIndex: indexPath.row];
  /*CGFloat fImgSize = _rowHgt - 1;
  //HrdRcdViewCtrl* pBldRcdVctrl = [self parentViewController];
  //BOOL bUpdActType = NO;
  
  UITableViewRowAction *walkAct = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"  " handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
    [_table setEditing:NO];
    [pApp updateHrateDataActType:nHrateId actType:1];
    [self updateRightIcon:indexPath];
  }];
  //blurAction.backgroundEffect = [UIVibrancyEffect effectForBlurEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
  //walkAct.backgroundColor = [UIColor lightGrayColor];
  walkAct.backgroundColor = [UIColor colorWithPatternImage:[pApp imageWithImage:[UIImage imageNamed:@"act-walking"] scaledToSize:CGSizeMake(fImgSize, fImgSize)]];
  
  UITableViewRowAction *runAct = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"  " handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
    [_table setEditing:NO];
    [pApp updateHrateDataActType:nHrateId actType:2];
    [self updateRightIcon:indexPath];
  }];
  //runAct.backgroundColor = [UIColor lightGrayColor];
  runAct.backgroundColor = [UIColor colorWithPatternImage:[pApp imageWithImage:[UIImage imageNamed:@"act-running"] scaledToSize:CGSizeMake(fImgSize, fImgSize)]];
  
  UITableViewRowAction *bikAct = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"  " handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
    // maybe show an action sheet with more options
    [_table setEditing:NO];
    [pApp updateHrateDataActType:nHrateId actType:3];
    [self updateRightIcon:indexPath];
  }];
  bikAct.backgroundColor = [UIColor colorWithPatternImage:[pApp imageWithImage:[UIImage imageNamed:@"act-biking"] scaledToSize:CGSizeMake(fImgSize, fImgSize)]];
  
  UITableViewRowAction *climbAct = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"  " handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
    [_table setEditing:NO];
    [pApp updateHrateDataActType:nHrateId actType:4];
    [self updateRightIcon:indexPath];
  }];
  //blurAction.backgroundEffect = [UIVibrancyEffect effectForBlurEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
  climbAct.backgroundColor = [UIColor colorWithPatternImage:[pApp imageWithImage:[UIImage imageNamed:@"act-climbing"] scaledToSize:CGSizeMake(fImgSize, fImgSize)]];
  
  
  UITableViewRowAction *groupAct = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"  " handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
    [_table setEditing:NO];
    [pApp updateHrateDataActType:nHrateId actType:5];
    [self updateRightIcon:indexPath];
  }];
  groupAct.backgroundColor = [UIColor colorWithPatternImage:[pApp imageWithImage:[UIImage imageNamed:@"act-group"] scaledToSize:CGSizeMake(fImgSize, fImgSize)]];*/
  
  //delAct
  /*UITableViewRowAction *delAct = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Del"  handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
  UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    // When style is set to UIAlertActionStyleDestructive, the button appears with red text
    UIAlertAction* deleteActionAction = [UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive
                                   handler:^(UIAlertAction * action) {*/
                                     // Perform your delete operation here...
                                     /*NSString* sKey = [_sortedKeys objectAtIndex: indexPath.row];
                                     NSInteger nHrateId = sKey.integerValue;
                                     
                                     //[_table beginUpdates];
                                     [self deleteHrateRow:nHrateId row:indexPath.row];
                                     //if(indexPath.section > 0)
                                     //[_table deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];*
                                     pApp.m_nLastHrtId = 0;
                                     pApp.m_nLastHrate = 0;
                                     pApp.m_nCurtAvgHrt = 0;
                                     
                                     //[_sortedKeys delete:];
                                     [_table reloadData];*/
                                     /*[self onDeleteHrtRowData:indexPath.row];
                                   }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel
                                   handler:^(UIAlertAction * action) {
                                      [_table setEditing:NO];
                                   }];
    
    [alert addAction:deleteAction];
    [alert addAction:cancelAction];
    
    //[alert setModalPresentationStyle:UIModalPresentationPopover];
    //UIPopoverPresentationController *popPresenter = [alert popoverPresentationController];
    //alert.popoverPresentationController.barButtonItem = button;
    //alert.popoverPresentationController.sourceView = self.view;
    
    HrdRcdViewCtrl* pvCtrl = [self parentViewController];
    if(pvCtrl != nil)
      [pvCtrl presentViewController:alert animated:YES completion:nil];
    
  }];
  delAct.backgroundColor = [UIColor lightGrayColor];
  
  //return @[delAct, climbAct, walkAct, bikAct];
  //return @[delAct, groupAct, climbAct, bikAct, runAct, walkAct];
  return @[delAct];*/
}

- (void) updateRightIcon:(NSIndexPath *)indexPath
{
  UITableViewCell* pCell = [_table cellForRowAtIndexPath:indexPath];
  if(pCell != nil) {
    HrdRcdViewCtrl* pVCtrl = [self parentViewController];
    [pVCtrl reloadHrateData];
    UIImageView* ivLeftArrow  = [self getRightImgView:indexPath.row vctrl:pVCtrl];
    if(ivLeftArrow != nil)
      pCell.accessoryView = ivLeftArrow;
  }
}

- (void) resetCellBgrd:(NSInteger)nRow
{
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:nRow inSection:0];
  UITableViewCell* pCell = [_table cellForRowAtIndexPath:indexPath];
  pCell.backgroundColor = [UIColor whiteColor];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
  return UITableViewCellEditingStyleDelete;// | UITableViewCellEditingStyleInsert;;
}

- (void) deleteHrateRow:(NSInteger)nHrateId row:(NSInteger)nIdx
{
  if(_sortedKeys.count == 0) {
    return;
  }
  NSInteger n = _sortedKeys.count;
  NSMutableArray* items = [NSMutableArray arrayWithArray:_sortedKeys];
  if(items != nil && items.count > 0) {
    [items removeObjectsAtIndexes:[NSIndexSet indexSetWithIndex:nIdx]];
    _sortedKeys = [NSArray arrayWithArray:items];
  }
  n = _sortedKeys.count;
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [pApp deleteRow:@"H_Rate" key:nHrateId];
  [pApp deleteRow:@"H_RateRng" key:nHrateId];
  [pApp deleteRow:@"H_RateItem" key:nHrateId];
  
  if ([self.delegate respondsToSelector:@selector(deleteRowInvoke)])
    [self.delegate deleteRowInvoke];
}
/*- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  //这里写你手指横向滑动需要处理的事件
  //return nil; 
  return @"Delete";
}*/

- (void)tableView:(UITableView *)tabView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
  if (editingStyle == UITableViewCellEditingStyleDelete) {
    _nTableEditRow = -1;
    _bDeleteItem = NO;
    // Ensure that if the user is editing a name field then the change is committed before deleting a row -- this ensures that changes are made to the correct event object.
    [_table endEditing:NO];
    
    /*AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext* managedObjectContext = pApp.managedObjectContext;
    
    // Delete the managed object at the given index path.
    NSManagedObject *rcdToDelete = [_dirList objectAtIndex:indexPath.row];
    [managedObjectContext deleteObject:rcdToDelete];
    
    // Update the array and table view.
    [m_nWgtArray removeObjectAtIndex:indexPath.row];
    [_table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    // Commit the change.
    NSError *error;
    if (![managedObjectContext save:&error]) {
      // Handle the error.
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      exit(-1);  // Fail
    }
    else {
      [_tabView reloadData];
    }*/
    //[_table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    /*NSArray * keySort = _sortedKeys;//[_dirList keysSortedByValueUsingSelector:@selector(caseInsensitiveCompare:)];
    NSString* key = [keySort objectAtIndex: indexPath.row];
    NSString* value = [_dirList objectForKey: key];
    [_sortedKeys removeObserver:value forKeyPath:key];*/
    NSMutableArray* items = [NSMutableArray arrayWithArray:_sortedKeys];
    [items removeObjectsAtIndexes:[NSIndexSet indexSetWithIndex:indexPath.row]];
    _sortedKeys = [NSArray arrayWithArray:items];
    
    [tabView reloadData];
    //[_table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    
    //[self performSelector:@selector(updateRowTags) withObject:nil afterDelay:0.0];
  }
}

@end
